<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img
        class="the_img"
        v-if="!this.avatar"
        src="../../assets/images/avatar.jpg"
        alt=""
      />
      <img class="the_img" v-else :src="this.avatar" alt="" />
      <!-- 按钮区域 -->
      <div class="btn-box">
        <input
          type="file"
          accept="image/*"
          style="display: none"
          ref="upPhoto"
          @change="onFileChange"
        />
        <el-button type="primary" icon="el-icon-plus" @click="chooseImg"
          >选择图片</el-button
        >
        <el-button
          type="success"
          icon="el-icon-upload"
          :disabled="avatar === ''"
          @click="upAvatar"
          >上传头像</el-button
        >
      </div>
    </div>
  </el-card>
</template>

<script>
import { upUserAvatarApi } from '@/utils/api'
export default {
  name: 'UserAvatar',
  data() {
    return {
      avatar: ''
    }
  },
  methods: {
    chooseImg() {
      // 模拟点击事件 点击display为none的上传文件input
      this.$refs.upPhoto.click()
    },
    onFileChange(e) {
      const files = e.target.files
      // console.log(files)
      if (files.length === 0) {
        this.avatar = ''
      } else {
        // this.avatar = URL.createObjectURL(files[0]) // 纯前端方法
        // 1. 创建 FileReader 对象
        const fr = new FileReader()
        // 2. 调用 readAsDataURL 函数，读取文件内容
        fr.readAsDataURL(files[0])
        // 3. 监听 fr 的 onload 事件
        fr.onload = (e) => {
          // 4. 通过 e.target.result 获取到读取的结果，值是字符串（base64 格式的字符串）
          this.avatar = e.target.result
          // 5. 调用接口, 传递给后台并根据返回结果给用户提示
        }
      }
    },
    async upAvatar() {
      // console.log(this.avatar)
      const { data: res } = await upUserAvatarApi(this.avatar)
      if (res.code !== 0) return this.$message.error('上传头像失败！')
      this.$message.success('上传头像成功！')
      this.$store.dispatch('getUserInfoActions')
    }
  }
}
</script>

<style lang="scss" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
}
.the_img {
  width: 350px;
  height: 350px;
}
</style>
